// pages/Protocol/ProtocolDetail/ProtocolDetail.js
import { queryUserIou , updateUserIou , queryUserSignature , signUserIou } from '../../../api/protocol';
import { getBrandConfig } from '../../../api/brand';
import { getUser , queryRealName } from '../../../api/user';
import Wxml2Canvas from '../../../utils/canvas/index';
import { amountStrDesc , formatNum } from '../../../utils/util';
const regeneratorRuntime = require('../../../common/runtime');
var jsPDF = require('../../../utils/pdf');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    protocolId: '',
    protocol: {
      diffTime: 0,
    },
    closeDay: 0,
    user: {},
    userId: wx.getStorageSync('userId'),
    isUserSelf: '1', // 是否是发布人，1：是，0：否
    isLend: '0', // 是否是借出，0：否，1：是，
    imgs: [],
    tempFilePath: '',
    imgWidth: '',
    imgHeight: '',
    filePath: '',
    show: false,
    remark: '', // 备注
    showSign: false,
    signList: [],
    swiperIndex: 0,
    actions: [
      {name: '发送至微信'},
    ],
    showDown: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if(options.protocolId){
      this.setData({
        protocolId: options.protocolId,
      })
      console.log(this.data.protocolId,'id')
      this._getBrandConfig();
    }
    this._queryUserSignature();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    let query = wx.createSelectorQuery();
    query.selectAll('.share_canvas').boundingClientRect(r => {
      console.log(r,'r')
    }).exec()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    let userId = wx.getStorageSync('userId')
    return {
      path: '/pages/Welcome/Welcome?scene='+userId,
    }
  },
  _getBrandConfig(){
    let _this = this;
    getBrandConfig({})
    .then(res => {
      if(res.success){
        _this.setData({
          closeDay: res.data[0].iouAutoCloseDay ?? 30,
          // closeDay: 1,
        })
        _this.getDetail();
      }else{
        wx.showToast
      }
    })
  },
  getDetail(){
    let _this = this;
    queryUserIou({protocolId: _this.data.protocolId})
    .then(res => {
      if(res.success){
        var element = res.data.content[0];
        if(element.status == '0'){
          if(!element.borrowUserSignatureImgUrl){
            isLend = '1';
          }
          if(!element.lendUserSignatureImgUrl){
            isLend = '0';
          }
        }
        var itemTime = element.createTime.replace(/-/g,'/')
        var createTime = new Date(itemTime).getTime();
        var nowTime = new Date().getTime();
        var diffTime = createTime - nowTime + parseInt(_this.data.closeDay) * 24 * 3600 * 1000;
        if(diffTime < 0 && element.status == '0'){
          element.status = '2'
        }
        element.diffTime = diffTime;
        if(element.otherImgUrl){
          element.otherImgUrlArr = element.otherImgUrl.split(',')
        }
        var isLend = '0';
        _this.setData({
          protocol: element,
          isUserSelf: element.createUserId == wx.getStorageSync('userId') ? '1' : '0',
          isLend: isLend,
        })
        if(element.createUserId != wx.getStorageSync('userId')){
          _this._getUser();
        }
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 获取用户信息和实名信息
  _getUser(){
    let _this = this;
    getUser()
    .then(res => {
      if(res.success){
        _this.setData({
          user: res.data,
        })
        if(res.data.realName){
          _this._queryRealName();
        }
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  _queryRealName(){
    let _this = this;
    queryRealName()
    .then(res => {
      if(res.success){
        _this.setData({
          idNumber: res.data.idNumber,
        })
        console.log(res.data.idNumber,'idNumber')
        console.log(_this.data.idNumber,'idNumber')
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 查看借条，借条转canvas
  async showIou(){
    let _this = this;
    return new Promise(async(resolve,reject) => {
      console.log(jsPDF,'jsPDF')
      const doc = await jsPDF.PDFDocument.create();
      console.log(doc,'doc')
      wx.showLoading({})
      var arr = [];
      try {
        var mainImg = await _this.canvasMain();
        console.log(mainImg,'mainImg')
        arr.push(mainImg);
        if(_this.data.protocol.borrowUserIdCardBackImgUrl || _this.data.protocol.borrowUserIdCardFrontImgUrl || _this.data.iouContent){
          var idcardImg = await _this.canvasIdImg();
          arr.push(idcardImg);
        }
        if(_this.data.protocol.otherImgUrl){
          var otherImg = await _this.canvasOtherImg();
          arr.push(otherImg);
        }
        let page = doc.addPage();
        console.log(arr[0],'arro')
        var files = await _this.downloadImg(arr[0]);
        console.log(files,'files')
        let img = await doc.embedPng(files);
        page.drawImage(img,0,0,560,840)
        if(arr[1]){
          let page1 = doc.addPage();
          var files1 = await _this.downloadImg(arr[1]);
          console.log(files1,'files')
          let img1 = await doc.embedPng(files1);
          page1.drawImage(img1,0,0,560,840)
        }
        if(arr[2]){
          let page2 = doc.addPage();
          var files2 = await _this.downloadImg(arr[2]);
          console.log(files2,'files')
          let img2 = await doc.embedPng(files2);
          page2.drawImage(img2,0,0,560,840)
        }
        // const pdfBytes = await doc.save()
        // console.log(pdfBytes,'pdfBytes')
        const docBase64 = await doc.saveAsBase64()
        console.log(docBase64,'base64')
        // const docBuffer = Buffer.from(docBase64, 'base64');
        // let filePath = 'tmp/' + parseInt(new Date().getTime() / 1000) + '.pdf';
        // console.log(docBuffer,'docBuffer')
        const filePath = `${wx.env.USER_DATA_PATH}/protocol.pdf`;
        wx.getFileSystemManager().writeFile({
          filePath,
          data: docBase64,
          encoding: 'base64',
          success: res=>{
            console.log(res,'res');
            _this.setData({filePath: filePath})
            resolve();
            // _this.shareFile();
            // wx.showModal({
            //   title: '温馨提示',
            //   content: '是否确认分享',
            //   complete: (res) => {
            //     if (res.confirm) {
            //       _this.shareFile();
            //     }
            //   }
            // })
          },
          fail: error=> {
            console.log(error,'error')
            reject(error);
          }
        })
        // wx.uploadFile({
        //   filePath: 'filePath',
        //   name: 'name',
        //   url: 'url',
        // })
      } catch (error) {
        // wx.showToast({
        //   title: error,
        //   icon: 'error',
        // })
        reject(error);
      }
      wx.hideLoading();
    })
  },
  getImg(imgs){
    return new Promise((resolve,reject) => {
      imgs.onload = () => {
        resolve();
      }
    })
  },
  canvasMain(){
    return new Promise((resolve,reject) => {
      let _this = this;
      wx.createSelectorQuery().select('#protocolCanvas')
      .fields({ node: true, size: true })
      .exec(async (res) => {
        const canvas = res[0].node;
        const { protocol } = _this.data;
        const ctx = canvas.getContext('2d')
        const dpr = 4;
        const width = 560 * dpr
        const height = 840 * dpr
        console.log(width,'wdith')
        canvas.width = width
        canvas.height = height
        ctx.clearRect(0, 0, width, height)
        ctx.fillStyle = '#FFFFFF'
        ctx.fillRect(0, 0, width, height);
        ctx.font = 'bold 112px sans-serif';
        ctx.fillStyle = '#333333'
        // 字体宽 12，高20
        // 标题
        ctx.fillText('个人借条',233 * dpr,40 * dpr)
        ctx.font = '40px sans-serif';
        // 第一行
        ctx.fillText('为',55 * dpr,71 * dpr);
        ctx.moveTo(65 * dpr, 75 * dpr);
        ctx.lineTo(130 * dpr, 75 * dpr);
        ctx.stroke();
        ctx.fillText(protocol.lendReason,70 * dpr,71 * dpr);
        ctx.fillText('，',131 * dpr,71 * dpr);
        // 第二行
        ctx.moveTo(55 * dpr, 95 * dpr);
        ctx.lineTo(103 * dpr, 95 * dpr);
        ctx.stroke();
        ctx.fillText(protocol.borrowName ? protocol.borrowName : '',55 * dpr,90 * dpr);
        ctx.fillText('向',104 * dpr,90 * dpr);
        ctx.moveTo(116 * dpr, 95 * dpr);
        ctx.lineTo(164 * dpr, 95 * dpr);
        ctx.stroke();
        ctx.fillText(protocol.lendName ? protocol.lendName : '',118 * dpr,90 * dpr);
        ctx.fillText('（证件类型：',164 * dpr,90 * dpr);
        ctx.moveTo(226 * dpr, 95 * dpr);
        ctx.lineTo(298 * dpr, 95 * dpr);
        ctx.stroke();
        ctx.fillText('居民身份证',230 * dpr,90 * dpr);
        ctx.fillText('，证件号码：',300 * dpr,90 * dpr);
        ctx.moveTo(375 * dpr, 95 * dpr);
        ctx.lineTo(500 * dpr, 95 * dpr);
        ctx.stroke();
        ctx.fillText(protocol.borrowIdCard ? protocol.borrowIdCard : '',378 * dpr,90 * dpr);
        ctx.fillText('）',503 * dpr,90 * dpr);
        // 第三行
        ctx.fillText('借取本金人民币',55 * dpr,110 * dpr);
        ctx.moveTo(139 * dpr, 115 * dpr);
        ctx.lineTo(350 * dpr, 115 * dpr);
        ctx.stroke();
        ctx.fillText(amountStrDesc(protocol.lendAmount),143 * dpr,110 * dpr);
        ctx.fillText('（￥',351 * dpr,110 * dpr);
        ctx.moveTo(371 * dpr, 115 * dpr);
        ctx.lineTo(500 * dpr, 115 * dpr);
        ctx.stroke();
        ctx.fillText(formatNum(protocol.lendAmount),371 * dpr,110 * dpr);
        ctx.fillText('）',503 * dpr,110 * dpr);
        // 第四行
        ctx.fillText('自',55 * dpr,130 * dpr);
        ctx.moveTo(66 * dpr, 135 * dpr);
        ctx.lineTo(146 * dpr, 135 * dpr);
        ctx.stroke();
        ctx.fillText(protocol.lendStartDate,68 * dpr,130 * dpr);
        ctx.fillText('出借，需在',146 * dpr,130 * dpr);
        ctx.moveTo(206 * dpr, 135 * dpr);
        ctx.lineTo(286 * dpr, 135 * dpr);
        ctx.stroke();
        ctx.fillText(protocol.lendEndDate,208 * dpr,130 * dpr);
        ctx.fillText('归还，还款方式为：',286 * dpr,130 * dpr);
        ctx.moveTo(382 * dpr, 135 * dpr);
        ctx.lineTo(503 * dpr, 135 * dpr);
        ctx.stroke();
        ctx.fillText(protocol.lendEndDate + ' ' + protocol.repaymentMode,384 * dpr,130 * dpr);
        // 第五行
        ctx.fillText('本借条自',55 * dpr,150 * dpr);
        ctx.moveTo(103 * dpr, 155 * dpr);
        ctx.lineTo(151 * dpr, 155 * dpr);
        ctx.stroke();
        ctx.fillText(protocol.lendName ? protocol.lendName : '',104 * dpr,150 * dpr);
        ctx.fillText('向',152 * dpr,150 * dpr);
        ctx.moveTo(163 * dpr, 155 * dpr);
        ctx.lineTo(211 * dpr, 155 * dpr);
        ctx.stroke();
        ctx.fillText(protocol.borrowName ? protocol.borrowName : '',164 * dpr,150 * dpr);
        ctx.fillText('支付借款本金时生效，支付方式为',211 * dpr,150 * dpr);
        ctx.moveTo(391 * dpr, 155 * dpr);
        ctx.lineTo(502 * dpr, 155 * dpr);
        ctx.stroke();
        ctx.fillText(protocol.paymentMode,392 * dpr,150 * dpr);
        ctx.fillText('。',503 * dpr,150 * dpr);
        // 第六行
        ctx.fillText('借款人邮寄地址为',55 * dpr,170 * dpr);
        ctx.moveTo(135 * dpr, 175 * dpr);
        ctx.lineTo(502 * dpr, 175 * dpr);
        ctx.stroke();
        ctx.fillText(protocol.borrowUserAddress ? protocol.borrowUserAddress : '',136 * dpr,170 * dpr);
        // 第七行
        ctx.moveTo(55 * dpr, 195 * dpr);
        ctx.lineTo(502 * dpr, 195 * dpr);
        ctx.stroke();
        ctx.fillText('。',503 * dpr,190 * dpr);
        // 第八页空白
        // 第九页
        ctx.fillText('双方保证本借条中约定的邮寄地址、联系电话等信息（以下统称送达地址）真实、准确、合法有效，能',55 * dpr,230 * dpr);
        // 第十页
        ctx.fillText('用于接受对方及法院发送的各类纸质或电子数据通知、信函、法律文书等。双方同意管辖法院以电子方',55 * dpr,250 * dpr)
        ctx.fillText('式（包括但不限于通过本借条所载联系电话、中国审判流程信息公开网、全国统一送达平台、人民法院',55 * dpr,270 * dpr)
        ctx.fillText('在线服务平台等）送达所有诉讼材料、诉讼文书及法律文书（包括并不限于判决书、裁定书、调解书、',55 * dpr,290 * dpr)
        ctx.fillText('传票、通知书等），本约定不影响任何一方及法院适用法律允许的其他方式送达。本约定持续适用于借',55 * dpr,310 * dpr)
        ctx.fillText('条履行期间、法院一审、二审、再审和执行期间。双方对送达地址作出变更的。应自变更之日起3个工',55 * dpr,330 * dpr)
        ctx.fillText('作日内书面告知对方，变更一方未履行告知义务或提供的信息有误、不确切导致送达不能或送达有误的，',55 * dpr,350 * dpr)
        ctx.fillText('由其自行承担所有法律后果。任何一方或法院为借条的履行、变更、解除和争议解决，按送达地址想对',55 * dpr,370 * dpr)
        ctx.fillText('方邮寄、发送相关文书时，若发生送达不成情形（包括但不限于收件人身份不明、无人签收、地址不详、',55 * dpr,390 * dpr)
        ctx.fillText('地址搬迁、长期未自取、电子数据被退回、拒收等），文书退回之日视为送达之日；按邮寄地址直接送',55 * dpr,410 * dpr)
        ctx.fillText('达文书的，若发生送达不成情形（包括但不限于收件人身份不明、无人签收、地址不详、地址搬迁、长',55 * dpr,430 * dpr)
        ctx.fillText('期未自取、电子数据被退回、拒收等），可以采用留置或张贴文书的方式送达，留置或张贴文书之日视',55 * dpr,450 * dpr)
        ctx.fillText('为送达之日',55 * dpr,470 * dpr)
        ctx.fillText('任何一方不履行或不完全履行本借条约定义务的，应当承担相应的违约责任，并赔偿由此给守约方造成',55 * dpr,490 * dpr)
        ctx.fillText('的损失，包括守约方为实现债权而支付的',55 * dpr,510 * dpr)
        ctx.font = 'bold 40px sans-serif';
        ctx.fillText('律师费、保全费、诉讼费、公告费、公证费、鉴定费',235 * dpr,510 * dpr)
        ctx.font = '40px sans-serif';
        ctx.fillText('等',465 * dpr,510 * dpr)
        ctx.fillText('本借条的制定、解释、履行及在履行过程中出现的、或与本借条有关的纠纷之解决，受中华人民共和国',55 * dpr,530 * dpr)
        ctx.fillText('现有效的法律（不含港澳台地区法律法规，不含冲突法）的约束。',55 * dpr,550 * dpr)
        ctx.fillText('本借条纠纷由',55 * dpr,570 * dpr)
        ctx.font = 'bold 40px sans-serif';
        ctx.fillText('出借人所在地或借款人所在地',115 * dpr,570 * dpr)
        ctx.font = '40px sans-serif';
        ctx.fillText('人民法院管辖。',245 * dpr,570 * dpr)
        ctx.fillText('立此为据。',55 * dpr,590 * dpr)
        ctx.fillText('备注：',55 * dpr,610 * dpr)
        if(protocol.otherPromises){
          var arr = [];
          var num = 0;
          var str = '';
          for (let index = 0; index < protocol.otherPromises.length; index++) {
            str += protocol.otherPromises[num];
            if(arr.length == 0){
              if(num == 42){
                num = 0;
                str = '';
                arr.push(str);
              }
            }else{
              if(num == 45){
                num = 0;
                str = '';
                arr.push(str);
              }
            }
            if(index == protocol.otherPromises.length - 1){
              arr.push(str);
            }
          }
          for (let index = 0; index < arr.length; index++) {
            const text = arr[index];
            ctx.fillText(text,index == 0 ? 85 * dpr : 55 * dpr,610 * dpr + index * 20 * dpr);
          }
        }else{
          ctx.fillText('无',85 * dpr,610 * dpr)
        }
        ctx.font = 'bold 40px sans-serif';
        ctx.fillText('出借人：',55 * dpr,670 * dpr)
        if(protocol.lendUserSignatureImgUrl){
          let imgs = canvas.createImage();
          imgs.src = protocol.lendUserSignatureImgUrl;
          await _this.getImg(imgs);
          ctx.drawImage(imgs,90 * dpr,654 * dpr,93 * dpr,33 * dpr);
        }
        ctx.fillText('借款人：',253 * dpr,670 * dpr);
        if(protocol.borrowUserSignatureImgUrl){
          let imgs = canvas.createImage();
          imgs.src = protocol.borrowUserSignatureImgUrl;
          await _this.getImg(imgs);
          ctx.drawImage(imgs,290 * dpr,654 * dpr,93 * dpr,33 * dpr);
        }
        ctx.font = '40px sans-serif';
        ctx.fillText('证件类型：居民身份证',55 * dpr,710 * dpr);
        ctx.fillText('证件号码：' + (protocol.borrowIdCard ? protocol.borrowIdCard : ''),55 * dpr,730 * dpr);
        ctx.fillText('联系电话：' + (protocol.borrowPhone ? protocol.borrowPhone : ''),55 * dpr,750 * dpr);
        wx.canvasToTempFilePath({
          canvas,
          quality: 1,
          destWidth: 560,
          destHeight: 840,
          success: res => {
              // 生成的图片临时文件路径
            const tempFilePath = res.tempFilePath;
            console.log(res,'tempath')
            _this.setData({
              tempFilePath,
            })
            resolve(tempFilePath)
          },
          fail: error => {
            reject(error)
          }
        })
      })
    })
  },
  // 绘制身份证图片信息
  canvasIdImg(){
    return new Promise((resolve,reject) => {
      let _this = this;
      wx.createSelectorQuery().select('#protocolCanvasId')
      .fields({ node: true, size: true })
      .exec(async (res) => {
        const canvas = res[0].node;
        const { protocol } = _this.data;
        const ctx = canvas.getContext('2d')
        const dpr = 4;
        const width = 560 * dpr
        const height = 840 * dpr
        console.log(width,'wdith')
        canvas.width = width
        canvas.height = height
        ctx.clearRect(0, 0, width, height)
        ctx.fillStyle = '#FFFFFF'
        ctx.fillRect(0, 0, width, height);
        ctx.font = '40px sans-serif';
        ctx.fillStyle = '#333333'
        if(protocol.borrowUserIdCardFrontImgUrl || protocol.borrowUserIdCardBackImgUrl){
          ctx.fillText('借款人身份证件：',55 * dpr,71 * dpr);
          if(protocol.borrowUserIdCardFrontImgUrl){
            let imgs = canvas.createImage();
            imgs.src = protocol.borrowUserIdCardFrontImgUrl;
            await _this.getImg(imgs);
            ctx.drawImage(imgs,55 * dpr,91 * dpr,220 * dpr,140 * dpr);
          }
          if(protocol.borrowUserIdCardBackImgUrl){
            let imgs = canvas.createImage();
            imgs.src = protocol.borrowUserIdCardBackImgUrl;
            await _this.getImg(imgs);
            ctx.drawImage(imgs,protocol.borrowUserIdCardFrontImgUrl && protocol.borrowUserIdCardBackImgUrl ? 285 * dpr : 55 * dpr,91 * dpr,220 * dpr,140 * dpr);
          }
          if(protocol.iouContent){
            ctx.fillText('出借人身份证件：',55 * dpr,251 * dpr);
            var imgArr = protocol.iouContent.split(',');
            for (let index = 0; index < imgArr.length; index++) {
              const img = imgArr[index];
              let imgs = canvas.createImage();
              imgs.src = img;
              await _this.getImg(imgs);
              ctx.drawImage(index == 1 ? 285 * dpr : 55 * dpr,271 * dpr,220 * dpr,140 * dpr);
            }
          }
        }else{
          if(protocol.iouContent){
            ctx.fillText('出借人身份证件：',55 * dpr,71 * dpr);
            var imgArr = protocol.iouContent.split(',');
            for (let index = 0; index < imgArr.length; index++) {
              const img = imgArr[index];
              let imgs = canvas.createImage();
              imgs.src = img;
              await _this.getImg(imgs);
              ctx.drawImage(index == 1 ? 285 * dpr : 55 * dpr,91* dpr,220 * dpr,160 * dpr);
            }
          }
        }
        wx.canvasToTempFilePath({
          canvas,
          quality: 1,
          destWidth: 560,
          destHeight: 840,
          success: res => {
              // 生成的图片临时文件路径
            const tempFilePath = res.tempFilePath;
            console.log(res,'tempath')
            // _this.setData({
            //   tempFilePath,
            // })
            resolve(tempFilePath)
          },
          fail: error => {
            reject(error)
          }
        })
      })
    })
  },
  // 绘制其他信息
  canvasOtherImg(){
    return new Promise((resolve,reject) => {
      let _this = this;
      wx.createSelectorQuery().select('#protocolCanvasOther')
      .fields({ node: true, size: true })
      .exec(async (res) => {
        const canvas = res[0].node;
        const { protocol } = _this.data;
        const ctx = canvas.getContext('2d')
        const dpr = 4;
        const width = 560 * dpr
        const height = 840 * dpr
        console.log(width,'wdith')
        canvas.width = width
        canvas.height = height
        ctx.clearRect(0, 0, width, height)
        ctx.fillStyle = '#FFFFFF'
        ctx.fillRect(0, 0, width, height);
        ctx.font = '40px sans-serif';
        ctx.fillStyle = '#333333'
        ctx.fillText('补充信息：',55 * dpr,71 * dpr);
        var imgArr = protocol.otherImgUrl.split(',');
        for (let index = 0; index < imgArr.length; index++) {
          const img = imgArr[index];
          let imgs = canvas.createImage();
          imgs.src = img;
          await _this.getImg(imgs);
          console.log(index%2,'index%2')
          let yushu = index%2;
          let num = parseInt(index / 2);
          let dx = yushu == 0 ? 55 * dpr : 285 * dpr;
          let dy = 91 * dpr + (num * 160 * dpr) + (num * 20 * dpr);
          console.log(dx,dy,'dx,dy')
          ctx.drawImage(imgs,dx ,dy,220 * dpr,160 * dpr);
        }
        wx.canvasToTempFilePath({
          canvas,
          quality: 1,
          destWidth: 560,
          destHeight: 840,
          success: res => {
              // 生成的图片临时文件路径
            const tempFilePath = res.tempFilePath;
            console.log(res,'tempath')
            // _this.setData({
            //   tempFilePath,
            // })
            resolve(tempFilePath)
          },
          fail: error => {
            reject(error)
          }
        })
      })
    })
  },
  downloadImg(img){
    console.log(img,'img')
    return new Promise((resolve,reject) => {
      wx.getFileSystemManager().readFile({
        filePath: img,
        encoding: 'base64',
        success: (res) => {
          console.log(res,'baseRes')
          resolve(res.data)
        },
        fail: error => {
          console.log('error')
          reject(error)
        }
      })
    })
  },
  // showIou(){
  //   let _this = this;
  //   var drawImgs = new Wxml2Canvas({
  //     width: 592,
  //     height: 840,
  //     element: 'canvas2',
  //     // background: '#f0f0f0',
  //     progress (percent) {
  //       console.log(percent,'percent')
  //     },
  //     finish(url) {
  //         console.log(url)
  //         let imgs = _this.data.imgs;
  //         imgs.push(url);
  //         _this.setData({
  //           imgs,
  //         })
  //         console.log(imgs,'imgs')
  //     },
  //     error (res) {
  //     }
  //   })
  //   let data = {
  //     list: [{
  //         type: 'wxml',
  //         class: '.share_canvas .draw_canvas',
  //         limit: '.share_canvas',
  //         x: 0,
  //         y: 0
  //     }]
  // }
  //   drawImgs.draw(data)
  // },
  shareFile(){
    let _this = this;
    let filePath = _this.data.filePath;
    wx.shareFileMessage({
      filePath: filePath,
      success: res=> {

      },
      fail: error => {
        wx.showToast({
          title: error,
          icon: 'error'
        })
      },
    })
  },
  // 下载手机
  downLoadIou(){
    let _this = this;
    let filePath = _this.data.filePath;
    wx.downloadFile({
      url: filePath,
      success: res=> {
        wx.showToast({
          title: '下载成功',
          icon: 'success'
        })
      },
      fail: error => {
        wx.showToast({
          title: error,
          icon: 'error'
        })
      },
    })
  },
  // 撤销借条
  cancelIou(){
    this.setData({show: true})
  },
  onClose(){
    this.setData({show: false})
  },
  onReamrkChange(e){
    this.setData({remark: e.detail})
  },
  // 确认撤销借条
  submitCancel(){
    let _this = this
    if(_this.data.remark == ''){
      wx.showToast({
        title: '请输入撤销理由',
        icon: 'none',
      });
      return;
    }
    updateUserIou({id: _this.data.protocol.id,status: '2',remark: _this.data.remark})
    .then(res => {
      if(res.success){
        wx.showToast({
          title: '撤销成功',
          icon: 'success',
        })
        _this.setData({show: false})
        _this.getDetail();
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 删除借条
  delIou(){
    let _this = this;
    wx.showModal({
      title: '',
      content: '清理后，您本人当前身份无法再次查看或操作该文件;请您放心，本操作不影响文件在其他签署人列表内的展示。',
      complete: (res) => {
        if (res.confirm) {
          updateUserIou({id: _this.data.protocol.id,isDelete: '1'})
          .then(res => {
            if(res.success){
              wx.showToast({
                title: '删除成功',
                icon: 'success',
              })
              wx.switchTab({
                url: '/pages/Tabbar/Protocol/Protocol'
              })
            }else{
              wx.showToast({
                title: res.errMessage,
                icon: 'none',
              })
            }
          })
        }
      }
    })
  },
  submitSign(){
    this.setData({
      showSign: true,
    })
  },
  // 获取用户签名列表信息
  _queryUserSignature(){
    let _this = this;
    queryUserSignature({})
    .then(res => {
      if(res.success){
        var list = res.data;
        list.push({'isAdd': '1'});
        _this.setData({
          signList: list,
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  goSign(e){
    let _this = this;
    let url = e.target.dataset.name||e.currentTarget.dataset.name;
    wx.navigateTo({
      url: `${url}`,
      events: {
        'updateSignature': function(data){
          _this._queryUserSignature();
        }
      }
    })
  },
  // 切换签名轮播图
  swiperChange(event){
    console.log(event)
    this.setData({swiperIndex: event.detail.current})
  },
  onSignClose(){
    this.setData({showSign: false});
  },
  // 完成签署
  submit(){
    let _this = this;
    if(_this.data.swiperIndex == _this.data.signList.length - 1){
      wx.showToast({
        title: '请选择签名后再进行操作',
        icon: 'none',
      });
      return;
    }
    const { user , protocol , idNumber } = _this.data;
    console.log(_this.data.signList,_this.data.swiperIndex,'signlist')
    var signatureImgUrl = _this.data.signList[_this.data.swiperIndex].signatureImgUrl
    console.log(signatureImgUrl,'signatureImgUrl')
    var params = protocol.lendUserSignatureImgUrl ? {
      'userIouId': protocol.id,
      'borrowUserSignatureImgUrl': signatureImgUrl,
      'borrowPhone': user.phone,
      'borrowName': user.realName,
      'borrowIdCard': idNumber,
      'lendUserSignatureImgUrl': protocol.lendUserSignatureImgUrl,
      'lendPhone': protocol.lendPhone,
      'lendName': protocol.lendName,
      'lendIdCard': protocol.lendIdCard,
    } : {
      'userIouId': protocol.id,
      'lendUserSignatureImgUrl': signatureImgUrl,
      'lendPhone': user.phone,
      'lendName': user.realName,
      'lendIdCard': idNumber,
      'borrowPhone': protocol.borrowPhone,
      'borrowName': protocol.borrowName,
      'borrowIdCard': protocol.borrowIdCard,
    }
    signUserIou(params)
    .then(res => {
      if(res.success){
        wx.switchTab({url: '/pages/Tabbar/Protocol/Protocol'});
        wx.showToast({
          title: '签署成功',
          icon: 'success'
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 下载借条
  async downloadIou(){
    await this.showIou();
    this.setData({showDown: true});
  },
  onDownClose() {
    this.setData({ showDown: false });
  },
  onSelect(event) {
    let _this = this;
    console.log(event.detail);
    if(event.detail.name == '发送至微信'){
      _this.shareFile();
    }
    if(event.detail.name == '下载'){
      _this.downLoadIou();
    }
  },
  // 补充信息
  suppIou(){
    let _this = this;
    wx.navigateTo({
      url: '/pages/Protocol/ReplenishProtocol/ReplenishProtocol?id=' + JSON.stringify(_this.data.protocol.id),
      events: function(data){
        _this.getDetail();
      }
    })
  },
})